// 代码块展开折叠功能
window.toggleCodeBlock = function (blockId) {
    const block = document.getElementById(blockId);
    const header = block.querySelector('.code-block-header');
    const content = block.querySelector('.code-block-content');
    const icon = header.querySelector('.toggle-icon');

    if (content.style.display === 'none') {
        // 展开
        content.style.display = 'block';
        icon.textContent = '▼';
        header.setAttribute('aria-expanded', 'true');
    } else {
        // 折叠
        content.style.display = 'none';
        icon.textContent = '►';
        header.setAttribute('aria-expanded', 'false');
    }
};

// 页面加载完成后初始化所有可折叠代码块
document.addEventListener('DOMContentLoaded', function () {
    // 查找所有带有 collapsible 类的代码块包装器
    const collapsibleBlocks = document.querySelectorAll('.code-block-wrapper.collapsible');

    collapsibleBlocks.forEach((block, index) => {
        const blockId = `collapsible-block-${index}`;
        block.id = blockId;

        // 获取标题文本（如果有的话）
        let title = block.getAttribute('data-title') || 'Details';

        // 创建标题元素
        const header = document.createElement('div');
        header.className = 'code-block-header';
        header.setAttribute('aria-expanded', 'false');
        header.innerHTML = `<span class="toggle-icon">►</span> ${title}`;
        header.onclick = function () { window.toggleCodeBlock(blockId); };

        // 创建内容容器
        const content = document.createElement('div');
        content.className = 'code-block-content';
        content.style.display = 'none';

        // 将代码块的原始内容移动到内容容器中
        while (block.firstChild) {
            content.appendChild(block.firstChild);
        }

        // 将标题和内容添加到代码块中
        block.appendChild(header);
        block.appendChild(content);
    });
});

// 获取前面所有相同语言且data-idx<10的代码块并执行
window.runBeforeCode = function (id, filePathId, lang) {
    const codeElement = document.getElementById(id);
    const filePathElement = document.getElementById(filePathId);
    if (!codeElement) return;


    // 获取所有与当前语言相同的代码块
    const allCodeBlocks = document.querySelectorAll(`textarea[data-lang="${lang}"]`);
    let combinedCode = '';

    // 遍历所有代码块，找出符合条件的代码块
    for (const block of allCodeBlocks) {

        if (block === codeElement) {
            combinedCode += block.value + '\n\n';
            break
        }

        combinedCode += block.value + '\n\n';
    }

    // 如果没有找到之前的代码块，显示提示
    if (combinedCode === '') {
        const resultId = 'result-' + id;
        let resultContainer = document.getElementById(resultId);
        if (!resultContainer) {
            const codeBlockWrapper = document.querySelector('#' + id).closest('.code-block-wrapper');
            resultContainer = document.createElement('div');
            resultContainer.id = resultId;
            resultContainer.className = 'code-execution-result';
            codeBlockWrapper.appendChild(resultContainer);
        }

        resultContainer.innerHTML = '<div class="result-header">执行结果：</div>';
        resultContainer.style.display = 'block';

        const div = document.createElement('div');
        div.className = 'result-info';
        div.textContent = '未找到之前的相同语言且data-idx<10的代码块';
        div.style.color = '#2196F3';
        resultContainer.appendChild(div);
        return;
    }

    const fileName = filePathElement ? filePathElement.value : '未知文件';

    // 在浏览器控制台打印文件名和合并后的代码
    console.log('========== 合并执行: ' + fileName + ' ==========');
    console.log(combinedCode);
    console.log('================================');

    // 获取或创建结果显示区域
    const resultId = 'result-' + id;
    let resultContainer = document.getElementById(resultId);
    if (!resultContainer) {
        const codeBlockWrapper = document.querySelector('#' + id).closest('.code-block-wrapper');
        resultContainer = document.createElement('div');
        resultContainer.id = resultId;
        resultContainer.className = 'code-execution-result';
        codeBlockWrapper.appendChild(resultContainer);
    }

    // 清空之前的结果
    resultContainer.innerHTML = '<div class="result-header">执行结果：</div>';
    resultContainer.style.display = 'block';

    // 显示加载状态
    const loadingDiv = document.createElement('div');
    loadingDiv.className = 'loading-indicator';
    loadingDiv.textContent = '正在执行...';
    resultContainer.appendChild(loadingDiv);

    // 准备发送请求数据
    const requestData = {
        id,
        lang,
        fileName: fileName,
        code: combinedCode
    };

    // 发送 POST 请求，直接接收 SSE 数据流
    const xhr = new XMLHttpRequest();
    xhr.open('POST', '/api/run-code', true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.responseType = 'text'; // 使用文本响应类型处理 SSE

    // 处理 SSE 数据流
    let buffer = '';

    xhr.onprogress = function () {
        // 获取新的响应文本
        const newData = xhr.responseText.substring(buffer.length);
        buffer += newData;

        // 处理接收到的 SSE 数据
        const lines = newData.split('\n');
        let eventType = '';
        let eventData = '';

        for (let i = 0; i < lines.length; i++) {
            const line = lines[i].trim();

            if (line.startsWith('event:')) {
                eventType = line.substring(6).trim();
            } else if (line.startsWith('data:')) {
                eventData = line.substring(5).trim();

                // 处理事件数据
                if (eventType && eventData) {
                    try {
                        const data = JSON.parse(eventData);
                        handleEvent(eventType, data, resultContainer);
                    } catch (e) {
                        console.error('解析 SSE 数据出错:', e);
                    }

                    // 重置事件类型和数据
                    eventType = '';
                    eventData = '';
                }
            }
        }
    };

    // 处理不同类型的事件
    function handleEvent(eventType, data, container) {
        // 移除加载指示器
        if (loadingDiv && loadingDiv.parentNode) {
            loadingDiv.remove();
        }

        const div = document.createElement('div');

        switch (eventType) {
            case 'start':
                div.className = 'result-start';
                div.textContent = data.message;
                break;
            case 'stdout':
                div.className = 'result-stdout';
                div.textContent = data.message;
                break;
            case 'stderr':
                div.className = 'result-stderr';
                div.textContent = data.message;
                div.style.color = '#f44336'; // 红色显示错误
                break;
            case 'exit':
                div.className = 'result-exit';
                div.textContent = data.message;
                if (data.code !== 0) {
                    div.style.color = '#f44336'; // 非零退出码用红色显示
                }
                break;
            case 'info':
                div.className = 'result-info';
                div.textContent = data.message;
                div.style.color = '#2196F3'; // 蓝色显示信息
                break;
            case 'error':
                div.className = 'result-error';
                div.textContent = data.message;
                div.style.color = '#f44336'; // 红色显示错误
                break;
            case 'close':
                button.textContent = originalText;
                button.style.backgroundColor = '';
                button.disabled = false; // 恢复按钮可点击状态
                console.log("%c Line:132 🌽", "color:#33a5ff", '关闭连接');
                // 关闭连接
                break;
        }

        container.appendChild(div);
    }

    // 处理请求完成
    xhr.onload = function () {
        if (xhr.status !== 200) {
            const div = document.createElement('div');
            div.className = 'result-error';
            div.textContent = '请求失败: ' + xhr.status + ' ' + xhr.statusText;
            div.style.color = '#f44336';
            resultContainer.appendChild(div);
        }
        // 恢复按钮状态
        button.textContent = originalText;
        button.style.backgroundColor = '';
        button.disabled = false;
    };

    // 处理请求错误
    xhr.onerror = function () {
        const div = document.createElement('div');
        div.className = 'result-connection-error';
        div.textContent = '连接中断或发生错误';
        div.style.color = '#f44336';
        resultContainer.appendChild(div);

        // 恢复按钮状态
        button.textContent = originalText;
        button.style.backgroundColor = '';
        button.disabled = false;
    };

    // 发送请求
    xhr.send(JSON.stringify(requestData));

    // 显示提示信息并禁用按钮
    const button = event.target;
    const originalText = button.textContent;
    button.textContent = '正在执行...';
    button.style.backgroundColor = '#73d13d';
    button.disabled = true; // 禁用按钮
};

// 将 runCode 函数定义为全局函数
window.runCode = function (id, filePathId, lang) {
    const codeElement = document.getElementById(id);
    const filePathElement = document.getElementById(filePathId);
    if (!codeElement) return;

    const code = codeElement.value;
    const fileName = filePathElement ? filePathElement.value : '未知文件';

    // 在浏览器控制台打印文件名和代码
    console.log('========== 文件: ' + fileName + ' ==========');
    console.log(code);
    console.log('================================');

    // 获取或创建结果显示区域
    const resultId = 'result-' + id;
    let resultContainer = document.getElementById(resultId);
    if (!resultContainer) {
        const codeBlockWrapper = document.querySelector('#' + id).closest('.code-block-wrapper');
        resultContainer = document.createElement('div');
        resultContainer.id = resultId;
        resultContainer.className = 'code-execution-result';
        codeBlockWrapper.appendChild(resultContainer);
    }

    // 清空之前的结果
    resultContainer.innerHTML = '<div class="result-header">执行结果：</div>';
    resultContainer.style.display = 'block';

    // 显示加载状态
    const loadingDiv = document.createElement('div');
    loadingDiv.className = 'loading-indicator';
    loadingDiv.textContent = '正在执行...';
    resultContainer.appendChild(loadingDiv);

    // 准备发送请求数据
    const requestData = {
        id,
        lang,
        fileName: fileName,
        code: code
    };

    // 发送 POST 请求，直接接收 SSE 数据流
    const xhr = new XMLHttpRequest();
    xhr.open('POST', '/api/run-code', true);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.responseType = 'text'; // 使用文本响应类型处理 SSE

    // 处理 SSE 数据流
    let buffer = '';

    xhr.onprogress = function () {
        // 获取新的响应文本
        const newData = xhr.responseText.substring(buffer.length);
        buffer += newData;

        // 处理接收到的 SSE 数据
        const lines = newData.split('\n');
        let eventType = '';
        let eventData = '';

        for (let i = 0; i < lines.length; i++) {
            const line = lines[i].trim();

            if (line.startsWith('event:')) {
                eventType = line.substring(6).trim();
            } else if (line.startsWith('data:')) {
                eventData = line.substring(5).trim();

                // 处理事件数据
                if (eventType && eventData) {
                    try {
                        const data = JSON.parse(eventData);
                        handleEvent(eventType, data, resultContainer);
                    } catch (e) {
                        console.error('解析 SSE 数据出错:', e);
                    }

                    // 重置事件类型和数据
                    eventType = '';
                    eventData = '';
                }
            }
        }
    };

    // 处理不同类型的事件
    function handleEvent(eventType, data, container) {
        // 移除加载指示器
        if (loadingDiv && loadingDiv.parentNode) {
            loadingDiv.remove();
        }

        const div = document.createElement('div');

        switch (eventType) {
            case 'start':
                div.className = 'result-start';
                div.textContent = data.message;
                break;
            case 'stdout':
                div.className = 'result-stdout';
                div.textContent = data.message;
                break;
            case 'stderr':
                div.className = 'result-stderr';
                div.textContent = data.message;
                div.style.color = '#f44336'; // 红色显示错误
                break;
            case 'exit':
                div.className = 'result-exit';
                div.textContent = data.message;
                if (data.code !== 0) {
                    div.style.color = '#f44336'; // 非零退出码用红色显示
                }
                break;
            case 'info':
                div.className = 'result-info';
                div.textContent = data.message;
                div.style.color = '#2196F3'; // 蓝色显示信息
                break;
            case 'error':
                div.className = 'result-error';
                div.textContent = data.message;
                div.style.color = '#f44336'; // 红色显示错误
                break;
            case 'close':
                button.textContent = originalText;
                button.style.backgroundColor = '';
                button.disabled = false; // 恢复按钮可点击状态
                console.log("%c Line:132 🌽", "color:#33a5ff", '关闭连接');
                // 关闭连接
                break;
        }

        container.appendChild(div);
    }

    // 处理请求完成
    xhr.onload = function () {
        if (xhr.status !== 200) {
            const div = document.createElement('div');
            div.className = 'result-error';
            div.textContent = '请求失败: ' + xhr.status + ' ' + xhr.statusText;
            div.style.color = '#f44336';
            resultContainer.appendChild(div);
        }
        // 恢复按钮状态
        button.textContent = originalText;
        button.style.backgroundColor = '';
        button.disabled = false;
    };

    // 处理请求错误
    xhr.onerror = function () {
        const div = document.createElement('div');
        div.className = 'result-connection-error';
        div.textContent = '连接中断或发生错误';
        div.style.color = '#f44336';
        resultContainer.appendChild(div);

        // 恢复按钮状态
        button.textContent = originalText;
        button.style.backgroundColor = '';
        button.disabled = false;
    };

    // 发送请求
    xhr.send(JSON.stringify(requestData));

    // 显示提示信息并禁用按钮
    const button = event.target;
    const originalText = button.textContent;
    button.textContent = '正在执行...';
    button.style.backgroundColor = '#73d13d';
    button.disabled = true; // 禁用按钮


};
